<?php

namespace app\withdrawal\controller;

use app\common\controller\Adminbase;
use app\common\controller\FormBuilder;
use app\common\controller\ListBuilder;
use app\model\User;
use app\model\Withdrawal as WithdrawalModel;
use think\Db;

class Push extends Adminbase
{
	public function index()
	{
		$model = 'Withdrawal';

		if ($this->request->isAjax()) {
			$map      = $this->buildParamsMap();
			$page     = input('page') ? input('page') : 1;
			$pageSize = input('limit') ? input('limit') : 20;

			$list   = WithdrawalModel::where($map)
				->where('type', 1)
				->field('*')
				->append(['status_text', 'withdrawal_status_text'])
				->withAttr('withdrawal_money', function ($value) {
					return $value > 0 ? number_format($value / 100, 2) : "0.00";
				})
				->withAttr('charge_money', function ($value) {
					return $value > 0 ? number_format($value / 100, 2) : "0.00";
				})
				->withAttr('money', function ($value) {
					return $value > 0 ? number_format($value / 100, 2) : "0.00";
				})
				->withAttr('auto_status', function ($value) {
					return $value !== null ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge">否</span>';
				})
				->withAttr('auto_type', function ($value) {
					$text = [1 => '微信', 2 => '支付宝', 3 => '银行卡'];
					return $value ? $text[$value] : '';
				})
				->withAttr('auto_msg', function ($value, $data) {
					$auto_status = $data['auto_status'];
					$auto_msg    = $value;
					$texts       = [
						0 => '<span class="layui-badge layui-bg-blue">未完成</span>',
						1 => '<span class="layui-badge layui-bg-green">已完成</span>',
						2 => '<span class="layui-badge">失败</span>',
						3 => '<span class="layui-badge layui-bg-orange">已撤销</span>',
					];
					if ($auto_status == 2 && $auto_msg) {
						$text = $texts[$auto_status];
						$text .= '<i class="layui-icon" style="font-size: 20px; color: red;" onmouseover="layer.tips(\'' . $auto_msg . '\',this,{tips: [1, \'#1A2426FF\'], time: 0});" onmouseout="layer.closeAll();">&#xe607;</i>';
						return $text;
					} else {
						if ($auto_status === null) {
							return '';
						}
						return $texts[$auto_status];
					}
				})
				->with(['user', 'record'])
				->page($page, $pageSize)
				->select();
			$total  = WithdrawalModel::where($map)->where('type', 1)->count();
			$result = ["code" => 0, "count" => $total, "data" => $list];
			return json($result);
		}
		$tabList = [
			['key' => '', 'value' => '全部'],
			['key' => WithdrawalModel::STATUS_WAIT, 'value' => '待审核'],
			['key' => WithdrawalModel::STATUS_COMPLETED, 'value' => '通过'],
			['key' => WithdrawalModel::STATUS_REJECTED, 'value' => '驳回'],
		];

		//生成列表数据
		$builder = new ListBuilder();
		$builder
			->setTabNav($tabList)
			->setTabName('status')
			->setDataUrl()
			->setAddBtn(false)
			->setDelAllBtn(false)
			->setDelBtn(false)
			->setSwitchTpl('amplifyTpl', 'image')
			->setModel($model)
			->setLimit()
			->addTableColumn('id', 'ID', 80, null, true)
			->addTableColumn('user_id', '用户ID', 100)
			->addTableColumn('nickname', '用户昵称', 120)
			->addTableColumn('name', '收款人姓名', 120)
			->addTableColumn('image', '收款码图片', 120, '#amplifyTpl')
			->addTableColumn('money', '打款金额' . '(元)', 120)
			->addTableColumn('withdrawal_money', '提现金额' . '(元)', 120)
			->addTableColumn('charge_money', '提现手续费' . '(元)', 150)
			->addTableColumn('status_text', '审核状态', 120)
			->addTableColumn('withdrawal_status_text', '提现状态', 120)
			->addTableColumn('auto_status', '是否自动打款', 120)
			->addTableColumn('auto_type', '自动打款类型', 120)
			->addTableColumn('auto_msg', '自动打款状态', 120)
			->addTableColumn('create_time', '申请时间', 200)
			->addTableOperation()
			->setFieldSelfBtn([
				['type' => 'form', 'title' => '审核', 'class' => 'layui-btn-normal', 'url' => url('audit'), 'field' => 'status', 'value' => '0'],
				['type' => 'confirm', 'title' => '确认打款', 'class' => 'layui-btn-normal', 'url' => url('confirm'), 'msg' => '是否确认已打款？', 'field' => 'withdrawal_status', 'value' => '1'],
			])
			->returnForm();

		$this->assign('module', 'user');
		return $this->fetch('admin@common/lists');
	}

	public function audit()
	{
		$id    = $this->request->param('id/d');
		$info  = WithdrawalModel::find($id);
		$model = 'Withdrawal';

		if ($this->request->isPost()) {
			$data = $this->request->post();
			if ($data['status'] == 2 && empty($data['remark'])) {
				return json(['code' => -1, 'msg' => '请填写拒绝原因']);
			}
			$save = [
				'status' => $data['status'],
				'remark' => $data['remark'],
			];
			if ($data['status'] == 1) {
				$save['withdrawal_status'] = 1;
			}
			Db::startTrans();
			//驳回需要退回用户提现余额
			$user_res = true;
			if ($data['status'] == 2) {
				$save['withdrawal_status'] = 3;
				$info                      = $info->getData();
				$user                      = User::field('id, money')->where('id', $info['user_id'])->find()->getData();
				$user_res                  = User::update([
					'id'    => $info['user_id'],
					'money' => $user['money'] + $info['withdrawal_money'],
				]);
			}
			$res = WithdrawalModel::where('id', $data['id'])->update($save);
			if ($res && $user_res) {
				Db::commit();
			}
			return json(['code' => 0, 'msg' => '操作成功']);
		}

		if (isset($id) && $id > 0) {
			$this->assign('id', $id);
			$this->assign('action', 2);
		}

		$text    = [0 => '待审核', 1 => '通过', 2 => '驳回'];
		$builder = new FormBuilder();
		$builder
			->setUrl('audit')
			->setModel($model)
			->setSuccessUrl()
			->addFormItem('status', 'radio', '审核状态', '', $text)
			->addFormItem('remark', 'textarea', '审核内容')
			->setFormData($info)
			->returnForm();
		$this->assign('is_verify', 0);
		return $this->fetch('admin@common/form');
	}

	public function confirm()
	{
		$id   = $this->request->param('id/d');
		$info = WithdrawalModel::find($id)->getData();
		if ($info['status'] != 1) {
			return json(['code' => -1, 'msg' => '提现记录未审核通过']);
		}
		if ($info['withdrawal_status'] == 2) {
			return json(['code' => -1, 'msg' => '提现记录已处理成功，请勿重复操作']);
		}
		$res = WithdrawalModel::where('id', $id)->update([
			'withdrawal_status' => 2,
		]);
		if ($res) {
			return json(['code' => 0, 'msg' => '操作成功']);
		}
		return json(['code' => -1, 'msg' => '操作失败']);
	}

}
